package com.superb.common.core.exception;

import cn.dev33.satoken.exception.*;
import com.alibaba.fastjson2.JSON;
import com.superb.common.core.enums.SuperbCode;
import com.superb.common.core.model.Result;
import feign.FeignException;
import jakarta.servlet.ServletException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.sql.SQLException;
import java.util.List;

/**
 * 全局异常捕获
 * @Author: ajie
 * @CreateTime: 2024-04-28 17:52
 */
@Slf4j
@RestControllerAdvice
public class GlobalException {


    /**
     * @author：莫杰
     * @remars：参数校验异常捕获，自定义返回校验结果
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> handlerException(MethodArgumentNotValidException e) {
        // 获取异常信息
        BindingResult exceptions = e.getBindingResult();
        // 判断异常中是否有错误信息，如果存在就使用异常中的消息，否则使用默认消息
        if (exceptions.hasErrors()) {
            List<ObjectError> errors = exceptions.getAllErrors();
            if (!errors.isEmpty()) {
                // 这里列出了全部错误参数，按正常逻辑，只需要第一条错误即可
                FieldError fieldError = (FieldError) errors.get(0);
                log.error("参数校验异常-->{}", fieldError.getDefaultMessage());
                return Result.error(fieldError.getDefaultMessage(), e.getMessage());
            }
        }
        return Result.error("参数校验异常！", e.getMessage());
    }

    /**
     * @author：莫杰
     * @remars：参数校验异常捕获，自定义返回校验结果
     * @param e
     * @return
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result<?> handlerException(HttpMessageNotReadableException e) {
        String message = e.getMessage();
        log.error("参数校验异常-->{}", message);
        // 获取异常信息
        return Result.error("参数类型错误，请检查请求参数后提交！！！", e.getMessage());
    }

    /**
     * @author：莫杰
     * @remars：自定义系统异常
     * @param e
     * @return
     */
    @ExceptionHandler(SuperbException.class)
    public Result<?> handlerException(SuperbException e) {
        log.error("自定义异常: {}", JSON.toJSONString(e.getCode()), e);
        // 获取异常信息
        if (e.getCode() != null) {
            return Result.error(e.getCode(), e.getMessage());
        }
        return Result.error("程序错误！", e.getMessage());
    }

    /**
     * @author：莫杰
     * @remars：自定义系统异常
     * @param e
     * @return
     */
    @ExceptionHandler(ServletException.class)
    public Result<?> handlerException(ServletException e) {
        log.error("Spring异常", e);
        return Result.error("程序错误！", e.getMessage());
    }

    /**
     * @author：莫杰
     * @remars：自定义系统异常
     * @param e
     * @return
     */
    @ExceptionHandler(FeignException.class)
    public Result<?> handlerException(FeignException e) {
        log.error("远程调用异常", e);
        return Result.error("程序错误！", e.getMessage());
    }

    /**
     * @author：莫杰
     * @remars：自定义系统异常
     * @param e
     * @return
     */
    @ExceptionHandler(SQLException.class)
    public Result<?> handlerException(SQLException e) {
        log.error("SQL异常", e);
        // 获取异常信息
        return Result.error("SQL异常！", e.getMessage());
    }

    /**
     * @author：莫杰
     * @remars：自定义系统异常
     * @param e
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    public Result<?> handlerException(NullPointerException e) {
        log.error("非空异常", e);
        // 获取异常信息
        return Result.error("非空异常！", e.getMessage());
    }

    /**
     * @author：莫杰
     * @remars：sa-token异常捕获
     * @param e
     * @return
     */
    @ExceptionHandler(NotRoleException.class)
    public Result<?> handlerException(NotRoleException e) {
        log.error("权限校验异常", e);
        // 获取异常信息
        return Result.error(SuperbCode.TOEKN_ROLE, e.getMessage());
    }

    /**
     * @author：莫杰
     * @remars：sa-token异常捕获
     * @param e
     * @return
     */
    @ExceptionHandler(value = NotLoginException.class)
    public Result<Object> handlerException(NotLoginException e) {
        log.error("token异常", e);
        return Result.error(SuperbCode.TOEKN_NOT_LOGIN, e.getMessage());
    }

    /**
     * @author：莫杰
     * @remars：sa-token异常捕获
     * @param e
     * @return
     */
    @ExceptionHandler(value = NotPermissionException.class)
    public Result<Object> handlerException(NotPermissionException e) {
        log.error("权限异常", e);
        return Result.error(SuperbCode.TOKEN_PERMISSION, e.getMessage());
    }

    /**
     * @author：莫杰
     * @remars：sa-token异常捕获
     * @param e
     * @return
     */
    @ExceptionHandler(value = DisableServiceException.class)
    public Result<Object> handlerException(DisableServiceException e) {
        log.error("账号封禁异常", e);
        return Result.error(SuperbCode.TOKEN_DISABLED, e.getMessage());
    }

    /**
     * @author：莫杰
     * @remars：sa-token异常捕获
     * @param e
     * @return
     */
    @ExceptionHandler(value = ApiDisabledException.class)
    public Result<Object> handlerException(ApiDisabledException e) {
        log.error("接口封禁异常", e);
        return Result.error(SuperbCode.API_DISABLED, e.getMessage());
    }

    /**
     * @author：莫杰
     * @remars：sa-token异常捕获
     * @param e
     * @return
     */
    @ExceptionHandler(value = NotSafeException.class)
    public Result<Object> handlerException(NotSafeException e) {
        log.error("二级认证异常", e);
        return Result.error(SuperbCode.TOKEN_SAFE, e.getMessage());
    }

    /**
     * @author：莫杰
     * @remars：SPRING BEAN异常
     * @param e
     * @return
     */
    @ExceptionHandler(BeanCreationException.class)
    public Result<?> handlerException(BeanCreationException e) {
        log.error(SuperbCode.BEAN_CREATE.getMessage(), e);
        return Result.error(SuperbCode.BEAN_CREATE, e.getMessage());
    }

    /**
     * @author：莫杰
     * @remars：SPRING BEAN异常
     * @param e
     * @return
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<?> handlerException(HttpRequestMethodNotSupportedException e) {
        log.error("REQUEST ERROR", e);
        return Result.error("错误的请求方法“" + e.getMessage().split("'")[1] + "”");
    }
    /**
     * @author：莫杰
     * @remars：SPRING BEAN异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public Result<?> handlerException(MethodArgumentTypeMismatchException e) {
        log.error("REQUEST ERROR", e);
        return Result.error("请求错误", e.getMessage());
    }
    /**
     * @author：莫杰
     * @remars：SPRING BEAN异常
     * @param e
     * @return
     */
    @ExceptionHandler(NoSuchBeanDefinitionException.class)
    public Result<?> handlerException(NoSuchBeanDefinitionException e) {
        log.error("Spring Bean异常", e);
        return Result.error("程序异常", e.getMessage());
    }

}
